package com.century.sjt.activity.login;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 炳基 on 2016/8/13.
 * 注册
 */
public class RegisterActivity extends BaseActivity {
    private static final String TAG = "RegisterActivity";
    @BindView(R.id.icon_position)
    TextView icon_position;
    @BindView(R.id.icon_jump)
    TextView icon_jump;
    @BindView(R.id.icon_phone)
    TextView icon_phone;
    @BindView(R.id.icon_unlock)
    TextView icon_unlock;
    @BindView(R.id.icon_eye)
    TextView icon_eye;
    @BindView(R.id.icon_add_friend)
    TextView icon_add_friend;
    @BindView(R.id.text_sjtxy)
    TextView aText;

    private EditText userNameEditText;
    private EditText passwordEditText;
    private EditText etInviteCode;
    private boolean isXY=false;
    private boolean isSeePwd=false;
    private Button btnRegister;
//
    private SjtTitleBar titleBar;


    Timer timer;
    TimerTask task;

    private LinearLayout layout_Country;
    private TextView tvCountryName,tvCountryNumber;
    private String countryNumber = "86";
    @Override
    protected void onCreate(Bundle arg0) {
        setContentView(R.layout.activity_register);
        super.onCreate(arg0);
        initView();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        userNameEditText = (EditText) findViewById(R.id.username);
        passwordEditText = (EditText) findViewById(R.id.password);
        btnRegister = (Button) findViewById(R.id.btn_register);
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        etInviteCode = (EditText) findViewById(R.id.invite_code);

        layout_Country = (LinearLayout) findViewById(R.id.layout_country);
        tvCountryName = (TextView) findViewById(R.id.country);
        tvCountryNumber = (TextView) findViewById(R.id.country_code);

        tvCountryName.setText(getString(R.string.text_china));
        tvCountryNumber .setText("+86");



    }

    @Override
    protected void onResume() {
        super.onResume();
        if (PreferenceManager.getInstance().getCountryCode()!=null){
            tvCountryName.setText(PreferenceManager.getInstance().getCountryName());
            String mobileCode = PreferenceManager.getInstance().getMobileCode();
            countryNumber = mobileCode;
            tvCountryNumber.setText("+" + mobileCode);
        }
    }

    @Override
    protected void initEvent() {

        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        icon_position.setTypeface(iconfont);
        icon_phone.setTypeface(iconfont);
        icon_jump.setTypeface(iconfont);
        icon_eye.setTypeface(iconfont);
        icon_unlock.setTypeface(iconfont);
        icon_add_friend.setTypeface(iconfont);
//        checkMobile();//检测手机是否注册
        checkInviteCode();//检测邀请码

//        btnSmsVcode();//点击获取校验码按钮

        //       标题栏
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleBar.setTitle(getResources().getString(R.string.tab_register));
//        btnRegister.setEnabled(false);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                register();

            }
        });
//        aText.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(RegisterActivity.this, TextActivity.class);
//                startActivity(intent);
//            }
//        });


        icon_eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                TipUtil.showToast("点击", RegisterActivity.this, 1);
                if (isSeePwd){
                    isSeePwd=false;
                }else {
                    isSeePwd=true;
                }
                if(isSeePwd){
                    //如果选中，显示密码
                    icon_eye.setText(getString(R.string.icon_eyes_closed));
//                    Log.e("main","1");
                    passwordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else{
                    //否则隐藏密码
                    icon_eye.setText(getString(R.string.icon_eye));
//                    Log.e("main","2");
                    passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

            }
        });

//        passwordEditText.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//             String pwd= passwordEditText.getText().toString();
//                if (pwd==null||pwd.equals("")){
//                    TipUtil.showToast("请输入密码", RegisterActivity.this, 1);
//                }else if (pwd.length()<6 || pwd.length()>16){
//                    TipUtil.showToast("密码长度要求6~16位", RegisterActivity.this, 1);
//                }
//            }
//        });
//



        layout_Country.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, ChooseCountryActivity.class);
                intent.putExtra("type","register");
                startActivityForResult(intent, Constant.REQUESTCODE_COUNTRY);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK){
            switch (requestCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
                case Constant.REQUESTCODE_COUNTRY:
                    Bundle bundle = data.getExtras();
                    String str = bundle.getString("countryName");//str即为回传的值
                    String mobileCode = bundle.getString("mobileCode");
                    countryNumber = mobileCode;
                    tvCountryName.setText(str);
                    tvCountryNumber.setText("+" + mobileCode);
                    userNameEditText.setText("");
                    break;
                case Constant.REQUESTCODE_LANGUAGE:
                    break;
                default:
                    break;
        }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 检测邀请码是否有效
     *
     */
    private void checkInviteCode() {
        etInviteCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                final String inviteCode = etInviteCode.getText().toString();
                if (!inviteCode.equals("")) {              //邀请码
                    //显示Progress Dialog
//                    TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), RegisterActivity.this);
                    String url = Constant.CheckInviteCode + etInviteCode.getText().toString().trim();
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            TipUtil.log("检查邀请码是否有效接口返回", response, 1);
                            TipUtil.closeProgressDialog();
                            try {
                                JSONTokener jsonParser = new JSONTokener(response);
                                JSONObject res = (JSONObject) jsonParser.nextValue();
                                String code = res.getString("code");

//                                Toast.makeText(SjtUserLoginActivity.this, code, Toast.LENGTH_LONG).show();
                                if (code.equals("200")) {//校验成功！

                                } else {
                                    String message = res.getString("message");
                                    TipUtil.showToast(message, RegisterActivity.this, 1);
                                }
                            } catch (Exception ex) {
                                //关闭进度条
                                TipUtil.closeProgressDialog();
                                TipUtil.showToast(getResources().getString(R.string.error_service), RegisterActivity.this, 1);
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //关闭进度条
                            TipUtil.closeProgressDialog();
                            TipUtil.showToast(getResources().getString(R.string.error_network), RegisterActivity.this, 1);
                        }
                    });

                    mQueue.add(stringRequest);
                }


            }
        });
    }


    /**
     * 注册按钮
     *
     */
    public void register() {

        final String mobile = userNameEditText.getText().toString();
        final String password = passwordEditText.getText().toString();
        final String inviteCode = etInviteCode.getText().toString().trim();
        if ("".equals(mobile)||null==mobile){
            TipUtil.showToast(getResources().getString(R.string.error_no_phone),RegisterActivity.this, 1);
        } else if (password.equals("") ||null==password) {
            TipUtil.showToast(getResources().getString(R.string.error_plerse_into_pwd), RegisterActivity.this, 1);
        }else if (password.length()<6 || password.length()>16){
            TipUtil.showToast(getResources().getString(R.string.error_isno_6or16_password), RegisterActivity.this, 1);
        }else if ("".equals(inviteCode)||null == inviteCode){
            TipUtil.showToast(getResources().getString(R.string.error_isno_initcode), RegisterActivity.this, 1);
        }else {
//            final AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this)
//                    .setCancelable(true)
//                    .show();
//            Window window = alertDialog.getWindow();
//            window.setContentView(R.layout.sjt_getmonilecode_alertdialog);
//            TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);
//            tv_message.setText("将给(" + tvCountryNumber.getText().toString() +") " + mobile + " 发送验证码");
//            Button btn_no = (Button) window.findViewById(R.id.btn_dialog_no);
//            btn_no.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    alertDialog.dismiss();
//                }
//            });
//            Button btn_ye = (Button) window.findViewById(R.id.btn_dialog_ye);
//            btn_ye.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    alertDialog.dismiss();
////                            getVCode.setStart(true);
//                    Regiscode(password, mobile, inviteCode);
//
//                }
//            });
            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
            builder.setMessage("将给(" + tvCountryNumber.getText().toString() +") " + mobile + " 发送验证码");
            builder.setCancelable(true);
            builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Regiscode(password, mobile, inviteCode);
                }
            });
            builder.setCancelable(false);
            builder.create().show();
//            sjtRegister(mobile, password, smsVCode,inviteCode,countryNumber);//世纪通注册
        }
    }

    /**
     * 获取短信校验码按钮计时
     *
     */
    public void btnSmsVcode() {
//        getVCode.setTextAfter(getResources().getString(R.string.btn_second)).setTextBefore(getResources().getString(R.string.btn_get_verification_code)).setLenght(60*1000);//设置倒计时
//        getVCode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                final String amobile=userNameEditText.getText().toString();
//                final AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this)
//                        .setCancelable(true)
//                        .show();
//                Window window = alertDialog.getWindow();
//                window.setContentView(R.layout.sjt_getmonilecode_alertdialog);
//                TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);
//                tv_message.setText("将给(+"+ countryNumber +") "+ amobile +" 发送验证码") ;
//                Button btn_no = (Button) window.findViewById(R.id.btn_dialog_no);
//                btn_no.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        alertDialog.dismiss();
//                    }
//                });
//                Button btn_ye = (Button) window.findViewById(R.id.btn_dialog_ye);
//                btn_ye.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        alertDialog.dismiss();
////                            getVCode.setStart(true);
//                        Regiscode(amobile,countryNumber);
//
//                    }
//                });
//
//            }
//
//        });
    }

    /**
     * 手机验证码
     *
     */
    private void Regiscode(final String password,final String mobile,final String inviteCode) {

        //加密密码
        byte[] encodePwd = password.getBytes();
        final String epwd = Base64Utils.encode(encodePwd);
        final String language = PreferenceManager.getInstance().getLanguageCode();
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getResources().getString(R.string.error_please_waitting), RegisterActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.RedisterCheckMobile, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                TipUtil.log("发送验证码", response, 1);
                TipUtil.closeProgressDialog();
                try {
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//校验成功！
                        Intent intent = new Intent();
                        intent.setClass(RegisterActivity.this, CheckMobileActivity.class);
                        intent.putExtra("mobile",mobile);
                        intent.putExtra("pwd",epwd);
                        intent.putExtra("inviteCode",inviteCode);
                        intent.putExtra("type","0");
                        startActivity(intent);
                    } else {
                        TipUtil.showToast(message, RegisterActivity.this, 1);
                    }
                } catch (Exception ex) {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    TipUtil.showToast(getResources().getString(R.string.error_service), RegisterActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //关闭进度条
                TipUtil.closeProgressDialog();
                TipUtil.showToast(getResources().getString(R.string.error_network), RegisterActivity.this, 1);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("mobileCode", countryNumber.trim());
                map.put("mobile",mobile.trim());
                map.put("inviteCode",inviteCode.trim());
                map.put("language", language);
                return map;
            }};

        mQueue.add(stringRequest);
    }
    /**
     * SJT注册
     *
     */
    private void sjtRegister(final String mobile, final String password, final String smsVCode, final String inviteCode,final String mobileCode) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), RegisterActivity.this);
        StringRequest regStringRequest = new StringRequest(Request.Method.POST, Constant.RegUserHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                TipUtil.closeProgressDialog();
                   TipUtil.log("sjt注册接口返回", response, 1);
                try {
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//注册成功
                        TipUtil.showToast(getResources().getString(R.string.error_redister_success), RegisterActivity.this, 1);
                        finish();

                    } else {
                        TipUtil.showToast(message, RegisterActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("error:", error.getMessage(), error);
            }
        }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //加密密码
                byte[] encodePwd = password.getBytes();
                final String epwd = Base64Utils.encode(encodePwd);
                Map<String, String> map = new HashMap<String, String>();
                map.put("mobile", mobile.trim());
                map.put("password", epwd.trim());
//                map.put("email",email.trim());
                map.put("validCode", smsVCode.trim());
                map.put("inviteCode", inviteCode.trim());
                map.put("mobileCode",mobileCode);
//                map.put("sysId", smsSysId);
                return map;
            }
        };
        mQueue.add(regStringRequest);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.cancelAll(this);
        timer = null;
        task = null;
    }

    public void back(View view) {
        finish();
    }

}
